package controller;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.Course;
import pojo.Student;
import pojo.Teacher;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.lang.System.getenv;
import static java.lang.System.out;

@Controller
public class CourseController {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();

    public CourseController() throws IOException {
    }

    //跳转到课程信息页面
    @RequestMapping("/courseList")
    public String courseList() {
        return "courseList.jsp";
    }

    //跳转到课程详情页面
    @RequestMapping("/course_detail")
    public String courseDetail() {
        return "course_detail.jsp";
    }

    //跳转到添加课程页面
    @RequestMapping("/course_add")
    public String course_add() {
        return "course_add.jsp";
    }

    /**
     * 课程列表加载
     */
    @RequestMapping(value = "/loadCourseList")
    public String loadCourseList(HttpSession session) throws Exception {
        int teacherId = Integer.parseInt(session.getAttribute("TEACHER_ID").toString().trim());
        out.println(teacherId);
        List<Course> get_courses = sqlSession.selectList("mapper.Course.findCourseByTeacherId", teacherId);

        out.println("输出所有课程信息");
        for (Course c : get_courses) {
            Course c1=new Course();
            c1.setT_id(teacherId);
            c1.setC_name(c.getC_name());
            int studentNumber=sqlSession.selectOne("mapper.Course.findCourseStudentNum",c1);
            c.setStudentNumber(studentNumber);
            System.out.println(c.getC_name()+studentNumber);
        }
        session.setAttribute("get_courses", get_courses);
        return "courseList.jsp";
    }

    /**
     * 选课详情加载
     */
    @RequestMapping(value = "/CourseListDetail")
    public String CourseListDetail(HttpSession session) throws Exception {
        String c_name = session.getAttribute("detail_name").toString().trim();
        int teacherId = (int) session.getAttribute("TEACHER_SESSION");
        out.println(c_name);
        Course c1 = new Course();
        c1.setC_name(c_name);
        c1.setT_id(teacherId);
        List<Course> get_courseStudents = sqlSession.selectList("mapper.Course.findStudentByTeacherIdAndCourseName", c1);
        List<Student> stuList = new ArrayList<>();
        for (Course s : get_courseStudents) {
            Student stu = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", s.getS_id());
            System.out.println(stu.getS_id());
            System.out.println(stu.getS_name());
            out.println(stu.getS_class());
            stuList.add(stu);
        }
        session.setAttribute("get_detailStudents", stuList);
        out.println("输出所有学生信息");
        for (Student s1 : stuList) {
            System.out.println(s1.getS_id());
            System.out.println(s1.getS_name());
        }
        return "course_detail.jsp";
    }

    /**
     * 课程端学生列表加载
     */
    @RequestMapping(value = "/loadCourseStudentList")
    public String loadCourseStudentList(HttpSession session) throws Exception {
        int teacherId=(int)session.getAttribute("TEACHER_SESSION");
        List<Student> get_courseStudents = sqlSession.selectList("mapper.Student.courseStudent",teacherId);
        session.setAttribute("get_courseStudents", get_courseStudents);
        out.println("课程列出所有学生信息");
        for (Student s : get_courseStudents) {
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
        }
        return "course_add.jsp";
    }

    /**
     * 课程详情中查询
     */
    @RequestMapping(value = "/findDetailStudentByStudentId")
    public String findDetailStudentByStudentId(Student student, HttpSession session) throws Exception {
        String c_name = session.getAttribute("detail_name").toString().trim();
        int teacherId = (int) session.getAttribute("TEACHER_SESSION");
        out.println(student.getS_id());
        out.println(c_name);
        Course c1 = new Course();
        c1.setC_name(c_name);
        c1.setT_id(teacherId);
        c1.setS_id(student.getS_id());
        Course get_detailStudents =sqlSession.selectOne("mapper.Course.findCourseByAll", c1);
        List<Student> stuList=new ArrayList<>();
        out.println(get_detailStudents.getS_id()+"获取数据库查到的学号");
        if (get_detailStudents!=null) {
            Student stu = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", get_detailStudents.getS_id());
            stuList.add(stu);
            session.setAttribute("get_detailStudents", stuList);
            System.out.println(stu.getS_id());
            System.out.println(stu.getS_name());
            out.println(stu.getS_class());
            return "course_detail.jsp";
        }
        return "course_detail.jsp";
    }

    /**
     * 课程端添加课程通过学生学号查询
     */
    @RequestMapping(value = "/findCourseStudentByStudentId")
    public String findCourseStudentByStudentId(Student student, HttpSession session) throws Exception {
        int s_id = student.getS_id();//搜素学生学号
        out.println("查询学生，后端java获取到的学生学号：" + student.getS_id());
        List<Student> get_courseStudents = sqlSession.selectList("mapper.Student.findStudentByStudentId", s_id);//找到包含该名字的学生
        if (get_courseStudents == null) {//查找为空
            out.println("数据为空");
        } else {
            session.setAttribute("get_courseStudents", get_courseStudents);//设置找到的学生为session对象
        }
        for (Student s : get_courseStudents) {
            out.println("通过学生学号查询学生结果如下：");
            System.out.println(s.getS_id());
            System.out.println(s.getS_name());
        }
        return "course_add.jsp";
    }

    /**
     * 选课详情中删除学生
     */
    @ResponseBody
    @RequestMapping("/deleteCourseStudent")
    public boolean deleteCourseStudent(Course course, HttpSession session) {
        try {
            int teacherId = (int) session.getAttribute("TEACHER_SESSION");
            String c_name=(String) session.getAttribute("detail_name");
            out.println("要删除的学生为"+course.getS_id()+"课程名称为"+c_name);
            Course c1 = new Course();
            c1.setT_id(teacherId);
            c1.setS_id(course.getS_id());
            c1.setC_name(c_name);
            int rows = sqlSession.delete("mapper.Course.deleteCourseStudent", c1);
            sqlSession.commit();
            if (rows > 0) {
                System.out.println("删除成功！");
                return true;
            } else {
                out.println("删除失败！");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("课程中删除学生时发生异常");
        }
        return false;
    }

    /**
     * 新建课程
     */
    @RequestMapping(value="/addCourse",consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Boolean addCourse(@RequestBody Map<String,String> selectedIds, HttpSession session) {
        String checkString=selectedIds.get("check");
        //按逗号分隔符字符串转化为Integer列表
        List<Integer> studentIds = Arrays.stream(checkString.split(","))
                .map(String::trim)
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        int teacherId = (int) session.getAttribute("TEACHER_SESSION");
        String c_name = (String) session.getAttribute("new_name");
        out.println("selectedIds:"+selectedIds);
        int rows=0;
        for (Integer studentId : studentIds) {
            Course c1 = new Course();
            c1.setC_name(c_name);
            c1.setT_id(teacherId);
            c1.setS_id(studentId);
            out.println(studentId);
            rows += sqlSession.insert("mapper.Course.addCourse", c1);
        }
        sqlSession.commit();
        if (rows > 0) {
            System.out.println("您成功插入了" + rows + "条课程数据！\n");
            return true;
        } else {
            System.out.println("执行插入操作失败！\n");
            return false;
        }
    }

    /**
     * 课程列表直接添加学生
     */
    @RequestMapping("/addCourseStudent")
    @ResponseBody
    public String addCourseStudent(int s_id, String s_name, String s_class, HttpSession session) {
        String c_name = session.getAttribute("course_name").toString().trim();
        int teacherId = (int) session.getAttribute("TEACHER_SESSION");
        //这里先通过数据库查询判断输入的信息是否正确，正确则进行后面的课程插入学生操作
        Student s1 = new Student();
        s1.setS_id(s_id);
        s1.setS_name(s_name);
        s1.setS_class(s_class);
        out.println(s_id + s_name + c_name + s_class);
        Course c0=new Course();
        c0.setC_name(c_name);
        c0.setT_id(teacherId);
        c0.setS_id(s_id);
        Course c00=sqlSession.selectOne("mapper.Course.findCourseByAll",c0);
        if(c00!=null){
            return "already";
        }
        else{
            Student s2 = sqlSession.selectOne("mapper.Student.findStudentByStudentIds", s_id);
            if (s2 != null) {//如果查询的结果不为空，则匹配填入的信息看是否正确
                if ((s1.getS_name().equals(s2.getS_name())) && (s1.getS_class().equals(s2.getS_class()))) {
                    //如果查到的信息完全匹配则将学生添加进课程
                    Course c1 = new Course();
                    c1.setS_id(s_id);
                    c1.setC_name(c_name);
                    c1.setT_id(teacherId);
                    int rows = sqlSession.insert("mapper.Course.addCourse", c1);
                    sqlSession.commit();
                    if (rows > 0) {
                        System.out.println("您成功插入了" + rows + "条学生数据！\n");
                        return "true";
                    } else {
                        System.out.println("执行插入操作失败！\n");
                        return "false";
                    }
                } else if ((!s1.getS_name().equals(s2.getS_name())) || (!s1.getS_class().equals(s2.getS_class()))) {
                    //如果这些信息不正确就是不匹配
                    System.out.println("输入的学生信息有误");
                    return "wronginfo";
                }
            } else {//在数据库中找不到输入的学生学号，则是输入错误
                out.println("输入的学号错误");
                return "wrongs_id";
            }
        }
        return "false";
    }

    //    获取课程名称
    @RequestMapping(value = "/acquireClassName")
    @ResponseBody
    public Boolean acquireClassName(String name, HttpSession session) throws Exception {
        session.setAttribute("course_name", name);
        return true;
    }

    //    获取详情的课程名称
    @RequestMapping(value = "/acquireClassNamed")
//    @ResponseBody
    public String acquireClassNamed(String name2, HttpSession session) throws Exception {
        out.println(name2 + "的课程详情");
        session.setAttribute("detail_name", name2);
        return "CourseListDetail";
    }
    //获取新建课程的名称
    @RequestMapping(value = "/acquireNewClassName")
    @ResponseBody
    public Boolean acquireNewClassName(String name3, HttpSession session) throws Exception {
        out.println(name3 + "的课程详情");
        String newName=name3.trim();
        Course c1=new Course();
        int teacherId=(int)session.getAttribute("TEACHER_SESSION");
        c1.setT_id(teacherId);
        c1.setC_name(newName);
        List<Course> course=sqlSession.selectList("mapper.Course.findCourseByTeacherIdAndCourseName",c1);
        //out.println(course.getC_name());
        if(course.size()!=0){
            out.println("失败");
            return false;
        }
        else{
            session.setAttribute("new_name", name3);
            out.println("成功");
            return true;
        }
    }
    /**
     * 根据课程名称查询课程信息
     */
    @RequestMapping(value = "/findCourseByCourseName")
    public String findCourseByCourseName(Course course, HttpSession session) throws Exception {
        int teacherId = (int) session.getAttribute("TEACHER_SESSION");//教师工号
        String c_name = course.getC_name();
        out.println("查询教师，后端java获取到的课程名称：" + course.getC_name());
        Course course1 = new Course();
        course1.setT_id(teacherId);
        course1.setC_name(c_name);
        List<Course> courseByC_name = sqlSession.selectList("mapper.Course.findCourseByCourseName", course1);//找到包含该名字且为该老师教的课程
        if (courseByC_name == null) {//查找为空
            out.println("数据为空");
        } else {//遍历看看
            for (Course c : courseByC_name) {
                Course c1=new Course();
                c1.setT_id(teacherId);
                c1.setC_name(c.getC_name());
                int studentNumber=sqlSession.selectOne("mapper.Course.findCourseStudentNum",c1);
                c.setStudentNumber(studentNumber);
                out.println("通过课程名称查询课程结果如下：");
                System.out.println(c.getT_id());
                System.out.println(c.getC_name());
                System.out.println(c.getS_id());
            }
            session.setAttribute("get_courses", courseByC_name);//设置找到的课程为session对象
        }

        return "courseList.jsp";
    }
}